package com.ym.b2b.commons.security;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;

@Controller
@RequestMapping("/security")
public class OAuth2Controller {

    Logger logger = Logger.getLogger(getClass());

    @RequestMapping("/trust.do")
    public void trust(HttpServletRequest request, HttpServletResponse response, HttpServletRequest req)
                                                                                                       throws IOException {
        String r = URLDecoder.decode(request.getQueryString(), getCharacterSet(request, response));
        JSONObject result = JSONObject.parseObject(r.substring(2));

        if (result.getBooleanValue("success") && "LOGIN".equalsIgnoreCase(result.getString("request_type"))) {
            response.sendRedirect(request.getContextPath() + "/index.jsp");

        } else if ("MODIFY".equalsIgnoreCase(result.getString("request_type"))) {
            response.setContentType("text/plain;charset=utf-8");
            response.getWriter().write(JSONObject.toJSONString(result));
            return;
        } else {

            if (StringUtils.isBlank(result.getString("result_message"))) {
                response.sendRedirect(request.getContextPath() + "/login.jsp");
            } else {
                response.sendRedirect(request.getContextPath() + "/login.jsp?e="
                                      + URLEncoder.encode(result.getString("result_message"), "UTF-8"));
            }
        }
    }

    private String getCharacterSet(HttpServletRequest request, HttpServletResponse response) {
        String encoding = null;
        if (encoding == null && request != null) {
            encoding = request.getCharacterEncoding();
        }
        if (encoding == null && response != null) {
            encoding = response.getCharacterEncoding();
        }
        if (encoding == null) {
            encoding = "UTF-8";
        }
        return encoding;
    }
}
